package com.itgm.jiayun_web_project.interceptor;

import com.itgm.jiayun_web_project.context.BaseContext;
import com.itgm.jiayun_web_project.pojo.Admin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("SessionInterceptor拦截器开始执行");
        //获取session
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI(); // 获取请求路径
        log.info("SessionInterceptor拦截器请求路径：" + requestURI);
        //判断uri是否为登录，如果是登录，则不拦截，否则拦截
        if (requestURI.contains("/login")) {
            return true;
        }
        //判断session中是否有用户，如果有，则不拦截，否则拦截
        if (session.getAttribute("username") == null){
            response.sendError(401,"用户未登录");
            //跳转到登录页面
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        if (session.getAttribute("username") != null){
            log.info("SessionInterceptor拦截器用户已登录");


            Object userId = session.getAttribute("userId"); // 获取用户id
            if (userId != null){
                BaseContext.setCurrentId((Long) userId); // 将用户id存入线程空间
                log.info("管理员id:{}已存入线程空间",userId);
            }else{
                log.info("管理员id为null");
            }

            log.info(requestURI,"用户已登录，放行...");
            return true;
        }
        return true;
    }
}
